# -*- coding: utf-8 -*-

import json
import logging

from django.views.generic import TemplateView
from django.utils.encoding import smart_unicode
from django.utils.decorators import method_decorator
from common.mch import db as mch_db
from common.utils.decorator import response_wrapper
from common.utils.api import token_required
from common.utils.tz import (
    utc_to_local_str
)
from django.views.decorators.http import require_POST

_LOGGER = logging.getLogger('hydra')


class MchView(TemplateView):
    def get(self, req):
        query_dct = req.GET.dict()
        from admin.views import add_query_fliter
        add_query_fliter(req, query_dct, mch_id_str='id')
        _LOGGER.info('MchView get mchs: %s, ', query_dct)

        items, total_count = mch_db.list_mch(query_dct)

        resp_items = []
        for item in items:
            data = item.as_dict()
            data['created_at'] = utc_to_local_str(data['created_at'])
            data['updated_at'] = utc_to_local_str(data['updated_at'])
            resp_items.append(data)

        return {'list': resp_items, 'page': query_dct.get('$page', 1),
                'size': len(resp_items), 'total_count': total_count}

    def post(self, req):
        param_dct = json.loads(req.body)
        mch = mch_db.create_mch(param_dct)
        return {'id': mch.id}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(MchView, self).dispatch(*args, **kwargs)


class SingleMchView(TemplateView):
    def get(self, req, mch_id):
        mch = mch_db.get_mch(id=int(mch_id))
        data = mch.as_dict()
        data['created_at'] = utc_to_local_str(data['created_at'])
        data['updated_at'] = utc_to_local_str(data['updated_at'])
        return data

    def post(self, req, mch_id):
        return self.put(req, mch_id)

    def put(self, req, mch_id):
        query_dct = json.loads(smart_unicode(req.body))
        mch_db.upsert_mch(query_dct, int(mch_id))
        return {'id': mch_id}

    def patch(self, req, mch_id):
        query_dct = json.loads(smart_unicode(req.body))
        mch_db.upsert_mch(query_dct, int(mch_id))
        return {'id': mch_id}

    def delete(self, req, mch_id):
        mch_db.delete_mch(int(mch_id))
        _LOGGER.info('delete mch: %s, user: %s', mch_id, req.user_id)
        return {'id': mch_id}

    @method_decorator(response_wrapper)
    @method_decorator(token_required)
    def dispatch(self, *args, **kwargs):
        return super(SingleMchView, self).dispatch(*args, **kwargs)


@require_POST
@response_wrapper
def update_mch_status(req):
    _LOGGER.info('update_status: %s', req.body)
    query_dct = json.loads(req.body)
    mch_db.update_status(query_dct, int(query_dct['id']))
    return {'id': query_dct['id']}